import React, {Component} from 'react';
import {message, Divider, Collapse, DatePicker, Radio, Space, Select, Button, Spin, Input} from "antd";
import {DownCircleOutlined} from "@ant-design/icons";
import moment from 'moment';
import { apiGetData, apiGetServiceData, apiGetCheckInData } from '@/request/hotelRoomStatus'
import { apiGetServiceClassify } from '@/request/cashier';
import CashierModal from "../../doctor/reservation/components/CashierModal";
import '../../doctor/reservation/style/style.less';
import TheImage from '@/components/TheImage';
import thirdParty from '@/assets/images/thirdParty.png';
import {scanEvent} from '@/utils/getCode'

const {RangePicker} = DatePicker;
const {Panel} = Collapse;

class Sider extends Component {
    constructor(props) {
        super(props)
        this.state = {
            searchOption: {},
            roomStatusOptions: [],
            roomStatus: "",
            otherRoomStatusOptions: [],
            otherRoomStatus: "",
            colorOption: [],
            dataService: [],
            beginTime: moment().format("YYYY-MM-DD"),
            endTime: moment().add(1, 'days').format("YYYY-MM-DD"),
            dates: [null,null],
            serviceId: '',
            thirdPartyVisible: false,
            thirdLoading: false,
            vtCode:''
        }
    }

    componentDidMount = async () => {
        this.setState({
            colorOption: [...this.props.colorOption],
        })
        await this.getService()
        await this.getData()
        if (!window.a) {
            window.addEventListener('keypress', this.scanWrapper, false);
            window.a = 1
        }
    }
    componentWillUnmount() {
        window.removeEventListener('keypress', this.scanWrapper, false);
        window.a = 0
    }
    getService = async () => {
        let hotel = await apiGetServiceClassify()
        if(hotel.code === 0){
            hotel.data.map( async v=>{
                if(v.serviceClassifyName === '酒店'){
                    let serviceClassifyId = v.serviceClassifyId
                    let res = await apiGetServiceData({pageNo:-1, pageSize:-1, approvalStatus: "T",serviceClassifyId})
                    if (res.code === 0 && res.data) {
                        this.setState({
                            dataService: res.data
                        })
                    }
                }
            })
        }
        
    }
    getData = async () => {
        this.props.openLoading();
        let params = {};
        let {serviceId, beginTime, endTime, roomStatus, otherRoomStatus} = this.state;
        if (serviceId) {
            params.serviceId = serviceId
        }
        if (beginTime && endTime) {
            params.beginTime = beginTime;
            params.endTime = endTime;
        }
        // console.log(roomStatus,otherRoomStatus)
        if (otherRoomStatus === '') {
            switch (roomStatus) {
                case 0:
                    params.roomStatus = 0;
                    break;
                case 5:
                    params.roomStatus = 5;
                    break;
                case 4:
                    params.roomStatus = 4;
                    break;
                case 1:
                    params.otherRoomStatus = 1;
                    break;
                default:
                    params.roomStatus = '';
                    break;
            }
        }
        if (roomStatus === '') {
            switch (otherRoomStatus) {
                case 0:
                    params.otherRoomStatus = 0;
                    break;
                case 2:
                    params.otherRoomStatus = 2;
                    break;
                case 3:
                    params.otherRoomStatus = 3;
                    break;
                default:
                    params.otherRoomStatus = ''
                    break;
            }
        }
        let res = await apiGetData(params)
        if (res.code === 0 && res.data) {
            let colorOption = this.props.colorOption;
            this.setState({
                // dataSource: res.data.roomStatusVos,
                roomStatusOptions: [
                    {label: '全部', value: '', num: res.data.total, color: ''},
                    {label: '空房', value: 0, num: res.data.emptyRoomCount, color: colorOption[0].value},
                    {label: '在住', value: 5, num: res.data.liveCount, color: colorOption[5].value},
                    {label: '预定', value: 4, num: res.data.bookCount, color: colorOption[4].value},

                ],
                otherRoomStatusOptions: [
                    {label: '不限', value: "", num: res.data.total, color: ''},
                    {label: '净房', value: 0, num: res.data.normalCount, color: colorOption[0].value},
                    {label: '保留', value: 1, num: res.data.retainCount, color: colorOption[1].value},
                    {label: '脏房', value: 2, num: res.data.dirtyCount, color: colorOption[2].value},
                    {label: '维修', value: 3, num: res.data.repairCount, color: colorOption[3].value},
                ],
            })
            // console.log('3')
            this.props.initData(res.data.roomStatusVos)
        }
    }
    // 房型选择
    onChangeRoomType = (value) => {
        // console.log(value)
        this.setState({
            serviceId: value
        }, () => {
            this.getData()
        })
    }
    // 日期选择
    onChangeDate = (e) => {
        console.log(e)
        // console.log(moment(e[0]).format("YYYY-MM-DD"))
        if (e) {
            this.setState({
                beginTime: moment(e[0]).format("YYYY-MM-DD"),
                endTime: moment(e[1]).format("YYYY-MM-DD"),
            }, () => {
                this.getData()
            })
        } else {
            this.setState({
                beginTime: "",
                endTime: "",
            })
        }
    }
    // 房态选择
    onChangeRoomStatus = ({target: {value}}) => {
        // console.log(value)
        this.setState({
            roomStatus: value,
            otherRoomStatus: ''
        }, () => {
            this.getData()
        })
    }
    // 更多筛选
    onChangeOtherRoomStatus = ({target: {value}}) => {
        // console.log(value)
        if (value===1){
            this.setState({
                otherRoomStatus: '',
                roomStatus: value
            }, () => {
                this.getData()
            })
        }else {
            this.setState({
                otherRoomStatus: value,
                roomStatus: ''
            }, () => {
                this.getData()
            })
        }

    }
    // 监听扫码枪
    scanWrapper = (e) => {
        let _that = this;
        scanEvent(e, async (code) => {
            // 监听了键盘输入或扫码枪
            // console.log(e,code,_that)
            if (code && _that.state.thirdPartyVisible) {
                let res = await apiGetCheckInData({qrCode:code})
                if (res.code === 0) {
                    _that.props.history.push(`/hotelRoomStatus/list/checkIn/${code}/${"-1"}`)
                }
            }
        });
    }
    // 输入框内容
    vtCodeValue = (v) => {
        // console.log(v)
        this.setState({
            vtCode: v.target.value
        })
    }
    // 条形码数字
    vtCodeClick = async () => {
        // console.log(this.state.vtCode)
        if (this.state.vtCode){
            let res = await apiGetCheckInData({vtCode:this.state.vtCode})
            if (res.code === 0) {
                this.props.history.push(`/hotelRoomStatus/list/checkIn/${"-1"}/${this.state.vtCode}`)
            }
        }
    }
    //核销扫码入住
    showCashierModal(e) {
        e.target.blur()
        this.setState({
            thirdPartyVisible: true,
        }, () => {
            // window.addEventListener('keypress', this.scanWrapper);
        })
    }

    //三方支付dialog关闭
    thirdPartyDialogClose = () => {
        this.setState({
            thirdPartyVisible: false
        }, () => {
            // window.removeEventListener('keypress', this.scanWrapper);
        })
    }
    // 禁止选择的日期
    disabledDate = (current) => {
        // Can not select days before today and today
        // return current && current < moment().startOf('day');
        let { beginTime,endTime,dates } = this.state
        // if (beginTime===''&&endTime===""){
        //     return current && current < moment().startOf('day');
        // }
        if (!dates) {
            return false;
        }
        const tooLate = dates[0] && current.diff(dates[0], 'days') > 1;
        const tooEarly = dates[1] && dates[1].diff(current, 'days') > 1;
        return !!tooEarly || !!tooLate;
    };
    onCalendarChange =(v)=>{
        console.log(v)
        this.setState({
            dates:v
        })
    }
    onOpenChange = (open) => {
        if (open) {
            this.setState({
                dates:[null, null],
                beginTime:"",
                endTime:"",
            })
        } else {
            this.setState({
                dates:null,
            })
        }
    };
    render() {
        let {
            roomStatusOptions,
            roomStatus,
            otherRoomStatusOptions,
            otherRoomStatus,
            dataService,
            thirdPartyVisible,
            thirdLoading,
            vtCode,
            beginTime,
            endTime,
            dates
        } = this.state;
        return (
            <div className='p-layout-box side-wrap'>
                <Button type="primary" onClick={(e) => this.showCashierModal(e)}>扫码入住</Button>
                <Divider/>
                <p><b>房型筛选</b></p>
                <br/>
                <Collapse
                    bordered={false}
                    defaultActiveKey={['2']}
                    expandIcon={({isActive}) => <DownCircleOutlined rotate={isActive ? 180 : 0}/>}
                    expandIconPosition={"end"}
                    className="site-collapse-custom-collapse"
                >
                    <Panel header="全部房型" key="1" className="site-collapse-custom-panel">
                        {/*<Checkbox.Group defaultValue={['']} onChange={this.onChangeRoomType}>*/}
                        {/*    {*/}
                        {/*        dataService.map(item=>{*/}
                        {/*            return <Checkbox value={item.serviceId}>{item.serviceName}</Checkbox>*/}
                        {/*        })*/}
                        {/*    }*/}
                        {/*</Checkbox.Group>*/}
                        <Select
                            allowClear
                            showSearch
                            optionFilterProp="children"
                            // mode="multiple"
                            placeholder="请选择房型"
                            // value={selectedItems}
                            onChange={this.onChangeRoomType}
                            style={{
                                width: '100%',
                            }}
                        >
                            {
                                dataService.map((item, index) => {
                                    return <options key={index} value={item.serviceId}>{item.serviceName}</options>
                                })
                            }
                        </Select>
                    </Panel>
                    <Panel header="日期筛选" key="2" className="site-collapse-custom-panel">
                        <RangePicker
                            format={'YY/MM/DD'}
                            // ranges={{
                                // "今天": [moment(), moment().add(1, 'days')],
                                // "本周": [moment().startOf('week'), moment().endOf('week')],
                                // '当月': [moment().startOf('month'), moment().endOf('month')],
                            //}}
                            disabledDate={this.disabledDate}
                            onChange={this.onChangeDate}
                            onCalendarChange={this.onCalendarChange}
                            onOpenChange={this.onOpenChange}
                            value={[beginTime?moment(beginTime):null, endTime?moment(endTime):null]}
                            // disabled={[false, true]}
                        />
                    </Panel>
                </Collapse>
                <p><b>房态筛选</b></p><br/>
                <Radio.Group value={roomStatus} optionType="button" size="large" onChange={this.onChangeRoomStatus}>
                    <Space className={"space"} direction="vertical" size={15}>
                        {
                            roomStatusOptions.map((item, index) => {
                                return <Radio key={index} value={item.value} className={"space-radio"}>
                                    <span className={"tip-color"} style={{backgroundColor: item.color}}></span>
                                    <span>{item.label}</span>
                                    <span className={"num"}>{item.num}</span>
                                </Radio>
                            })
                        }
                    </Space>
                </Radio.Group>
                <br/>
                <p><b>更多筛选</b></p><br/>
                <Radio.Group value={otherRoomStatus} optionType="button" size="large"
                             onChange={this.onChangeOtherRoomStatus}>
                    <Space className={"space other"} direction="vertical" size={15}>
                        {
                            otherRoomStatusOptions.map((item, index) => {
                                return <Radio key={index} value={item.value} className={"space-radio"}>
                                    <span className={"tip-color"} style={{backgroundColor: item.color}}></span>
                                    <span>{item.label}</span>
                                    <span className={"num"}>{item.num}</span>
                                </Radio>
                            })
                        }
                    </Space>
                </Radio.Group>
                <CashierModal
                    title="扫码入住"
                    width={600}
                    visible={thirdPartyVisible}
                    onCancel={this.thirdPartyDialogClose}
                    footer={
                        <div className='completion-button-group'>
                            <div onClick={this.thirdPartyDialogClose} className='dialog-footer-button'>
                                <div>取消入住</div>
                            </div>
                        </div>
                    }
                >
                    <Spin spinning={thirdLoading}>
                        <div className='third-party-box'>
                            <TheImage src={thirdParty} width={306} height={188} preview={false}/>
                            <div>请使用扫码枪，扫码客户预约的宠物酒店房间订单二维码</div>
                            <div className="third-party-input">
                                <Input type="number" size='middle' style={{ width: 200 }} placeholder='输入条形码数字' onChange={(e) => { this.vtCodeValue(e) }} />
                                <Button className="third-party-btn" type="large" onClick={() => {this.vtCodeClick()}}>查询</Button>
                            </div>
                        </div>
                    </Spin>
                </CashierModal>
            </div>
        );
    }
}

export default Sider;
